# ipv4 space by country code
# carlos@lacnic.net 20111220
# version 0.2

#===============================================================================
# Copyright (c) 2011 LACNIC - Latin American and Caribbean Internet 
# Address Registry
# 
# Permission is hereby granted, free of charge, to any person 
# obtaining a copy of this software and associated documentation 
# files (the "Software"), to deal in the Software without 
# restriction, including without limitation the rights to use, copy, 
# modify, merge, publish, distribute, sublicense, and/or sell copies 
# of the Software, and to permit persons to whom the Software is 
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be 
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
# SOFTWARE.
#===============================================================================

import sys
import argparse
from delegated_api import Delegated

# helper functions
def add(a,b):
	return a+b
## end helper functions

## init vars
dash24s= {}
p_delegated_file = 'data/delegated-lacnic-latest'

## parse command line

parser = argparse.ArgumentParser(description='Count IP address space for one or more country codes.')
parser.add_argument('p_ccodes', metavar='p_ccodes', type=str, nargs='+', help='Country Codes in ISO 2-character format or ALL for all countries.')
parser.add_argument('-f', '--delegated-file', dest='p_filename', type=str, default=p_delegated_file, help='Delegated stats file path')
args = parser.parse_args()

## create delegated parser
try:
	dlg = Delegated(args.p_filename)
except:
	sys.stderr.write('Unable to open file %s\n' % (args.p_filename))
	sys.exit(1)

## process command line

if len(args.p_ccodes)>1:	
	for country in args.p_ccodes:
		print "Processing delegated for cc %s" % (country)
		dlg.add_filter(cc=country)
		dlg.add_filter(type='ipv4')
		dlg.read_delegated()
		dash24s[country] = dlg.get_ip_count()/256
		dlg.reset()
		print "/24s count for country code %s:\t%s" % (country, dash24s[country])
else:
	dlg.read_delegated()
	dash24s['all'] = dlg.get_ip_count()/256

print "Grand Total %s" % reduce(add, dash24s.values())

## END #####################################################################